package vip.liux.backend.infrastructure.excel.converters;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.text.ParseException;
import java.util.Date;

import static vip.liux.backend.infrastructure.constants.GlobalConstant.DATE_TIME_FORMAT;

/**
 * Date and string converter
 *
 * @author JiaDu
 * @version 1.0.0
 * @since 2023/10/12
 */
public enum DateStringConverter implements Converter<Date> {

    /**
     * 实例
     */
    INSTANCE;

    @Override
    public Class<?> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) throws ParseException {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return DateUtils.parseDate(cellData.getStringValue());
        } else {
            FastDateFormat formatter = FastDateFormat
                .getInstance(contentProperty.getDateTimeFormatProperty().getFormat());
            return formatter.parse(cellData.getStringValue());
        }
    }

    @Override
    public WriteCellData<String> convertToExcelData(Date value, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) {
        FastDateFormat formatter;
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            formatter = DATE_TIME_FORMAT;
        } else {
            formatter = FastDateFormat.getInstance(contentProperty.getDateTimeFormatProperty().getFormat());
        }
        return new WriteCellData<>(formatter.format(value));
    }

}
